package co.recloud.ariadne.thread;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import co.recloud.ariadne.request.Request;
import co.recloud.ariadne.response.Response;
import co.recloud.ariadne.server.DataServer;

public class DataThread extends Thread {
	private ServerSocket serverSocket;
	private Socket socket;
	private boolean isServer;

	public DataThread(ServerSocket serverSocket) {
		this.serverSocket = serverSocket;
		isServer = true;
	}

	public DataThread(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		if (isServer) {
			while (true) {
				Socket client;
				if (serverSocket.isClosed()) {
					try {
						serverSocket.bind(serverSocket.getLocalSocketAddress());
					} catch (Exception e) {
						e.printStackTrace();
						break;
					}
				}
				try {
					client = serverSocket.accept();
					ThreadPool.startThread(new DataThread(client));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} else {
			DataServer server = new DataServer();
			ObjectInputStream in = null;
			ObjectOutputStream out = null;
			try {
				in = new ObjectInputStream(socket.getInputStream());
				out = new ObjectOutputStream(
						socket.getOutputStream());
				while(socket.isConnected()) {
					Request request = (Request) in.readObject();
					Main.setTime(request.getTime());
					Response response = server.serve(request);
					out.writeObject(response);
					out.flush();
				}
			} catch (EOFException eof) {
				try {
					in.close();
					out.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if(socket != null) {
					try {
						socket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}
